/**
 * Created by coder on 2018/1/11.
 */
import {ACTION_UPDATE_ERROR_MAP} from '../store/action'

const updateErrorMap = (newCell) => {
	return (dispatch,getState) => {
		const {errorMap,cells} = getState();
		let newErrorMap = errorMap.slice();

		__updateErrorMap(newCell,newErrorMap,cells);
		//this.props.setErrorMap(newErrorMap);
		dispatch({
			type:ACTION_UPDATE_ERROR_MAP,
			payload:{
				errorMap:newErrorMap
			}
		});
	}
};

const __updateErrorMap = (newCell,errorMap,cells) => {
	let left = parseInt(newCell.x/3)*3;
	let top = parseInt(newCell.y/3)*3;
	let right = left+3;
	let bottom = top+3;

	[0,1,2].map((y) => {
		[0,1,2].map((x) => {
			errorMap[(top+y)*9+left+x] = hasError(left+x,top+y,cells);
		})
	});

	for(let i=0;i<left;i++){
		errorMap[newCell.y*9+i] = hasError(i,newCell.y,cells);
	}

	for(let i=0;i<top;i++){
		errorMap[i*9+newCell.x] = hasError(newCell.x,i,cells);
	}

	for(let i=right;i<9;i++){
		errorMap[newCell.y*9+i] = hasError(i,newCell.y,cells);
	}

	for(let i=bottom;i<9;i++){
		errorMap[i*9+newCell.x] = hasError(newCell.x,i,cells);
	}

};

const hasError = (x,y,cells) => {
	const curCell = cells[y*9+x];
	if(curCell.data === 0)
		return false;

	for(let i=0;i<9;i++){
		if(i === curCell.y)
			continue;
		let item = cells[i*9+curCell.x];
		if(item.data === curCell.data)
			return true;
	}

	for(let i=0;i<9;i++){
		if(i === curCell.x)
			continue;
		let item = cells[curCell.y*9+i];
		if(item.data === curCell.data)
			return true;
	}

	let xx = parseInt(curCell.x/3)*3;
	let yy = parseInt(curCell.y/3)*3;

	for(let i=0;i<3;i++){
		for(let j=0;j<3;j++){
			if(xx + i === curCell.x || yy + j === curCell.y)
				continue;
			let item = cells[(yy + j)*9+xx + i];
			if(item.data === curCell.data)
				return true;
		}
	}

	return false;
};

export default updateErrorMap;